<template>
  <div class="sc-design">
    <div>
      <q-form @submit="onSubmit" ref="loginForm">
        <q-tabs
          v-model="loginType"
          active-color="primary"
          indicator-color="primary"
          align="left"
          :breakpoint="0"
          narrow-indicator
          class="text-black"
          inline-label
          @update:model-value="tabChange"
        >
          <q-tab
            :name="loginTypes.usernameLogin"
            icon="person"
            label="用户登录"
          />
          <q-tab
            :name="loginTypes.wechatLogin"
            icon="wechat"
            label="微信登录"
          />
        </q-tabs>
        <div class="q-gutter-y-sm">
          <q-tab-panels v-model="loginType" class="text-center">
            <q-tab-panel
              :name="loginTypes.usernameLogin"
              class="q-col-gutter-y-sm"
            >
              <div class="row">
                <div class="col">
                  <q-input
                    outlined
                    clearable
                    clear-icon="cancel"
                    v-model="username"
                    dense
                    placeholder="用户名"
                    square
                    lazy-rules
                    :rules="[
                      (val) => (val && val.length > 0) || '请输入用户名',
                    ]"
                  >
                    <template v-slot:prepend>
                      <q-icon name="person" />
                    </template>
                  </q-input>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <q-input
                    outlined
                    clearable
                    clear-icon="cancel"
                    :type="isPwd ? 'password' : 'text'"
                    v-model="password"
                    dense
                    debounce="1000"
                    placeholder="密码"
                    square
                    lazy-rules
                    :rules="[(val) => (val && val.length > 0) || '请输入密码']"
                  >
                    <template v-slot:prepend>
                      <q-icon name="lock" />
                    </template>
                    <template v-slot:append>
                      <q-icon
                        :name="isPwd ? 'visibility_off' : 'visibility'"
                        class="cursor-pointer"
                        @click="isPwd = !isPwd"
                      />
                    </template>
                  </q-input>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <q-btn
                    dense
                    unelevated
                    label="登 录"
                    size="17px"
                    color="primary q-mt-sm"
                    class="full-width no-border-radius"
                    type="submit"
                    :loading="loginLoading"
                  >
                    <template v-slot:loading>
                      <q-spinner-ios class="on-left" />
                      登录....
                    </template>
                  </q-btn>
                </div>
              </div>
            </q-tab-panel>

            <q-tab-panel
              :name="loginTypes.wechatLogin"
              class="q-col-gutter-y-sm"
            >
              <q-img :src="qrcode_url" ratio="1" spinner-color="white" />
            </q-tab-panel>
          </q-tab-panels>
        </div>
      </q-form>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { useUserStore } from "src/stores/user";

import {
  getUserLoginQrcode,
  getVideoUserInfo,
  recodeVideoUser,
} from "src/api/rooms";

import { login } from "src/api/user";

const $q = useQuasar();
const router = useRouter();
const userStore = useUserStore();

defineOptions({
  name: "Login",
});

const loginTypes = reactive({
  usernameLogin: "usernameLogin",
  wechatLogin: "wechatLogin",
});


const loginType = ref(loginTypes.usernameLogin);
const username = ref("");
const password = ref("");

const isPwd = ref(true);
const loginLoading = ref(false);

const qrcode_url = ref("");
var room = null;
var interval = null;

function getLoginQrcode() {
  $q.loading.show();
  getUserLoginQrcode()
    .then((res) => {
      console.log(res);

      if ("image_url" in res) {
        qrcode_url.value = res.image_url;
        room = res.room;
      }
      $q.loading.hide();
      startPolling();
    })
    .catch((error) => {
      console.log(error);
    });
}

function startPolling() {
  interval = setInterval(() => {
    getVideoUser();
  }, 3000); // 每3秒钟请求一次
}

function stopPolling() {
  console.log(interval);
  if (interval) {
    clearInterval(interval);
  }
}

function getVideoUser() {
  const params = {
    room: room,
  };
  console.log(params);
  getVideoUserInfo(params).then((res) => {
    console.log("interval:", res);
    if (res.status_code === 0) {
      stopPolling();
      const params = {
        openid: res.data.openid,
        nickname: res.data.nickname,
        name: res.data.name,
        telephone: res.data.telephone,
        sex: res.data.sex,
        province: res.data.province,
        city: res.data.city,
        country: res.data.country,
        language: res.data.language,
        headimgurl: res.data.headimgurl,
        qr_scene_str: res.data.qr_scene_str,
        role_id: res.data.role_id,
      };

      recordVideoLoginUser(params);
    }
  });
}

function recordVideoLoginUser(params) {
  recodeVideoUser(params)
    .then((res) => {
      if (res.status_code === 200) {
        userStore.setUserInfo(res);
        router.replace("/");
      } else {
        $q.dialog({
          title: "提示:",
          message: "扫码登录失败!",
        });
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

const tabChange = (value) => {
  if (value == loginTypes.wechatLogin) {
    getLoginQrcode();
  } else {
    stopPolling();
  }
};

function onSubmit() {
  loginLoading.value = true;
  const params = {
    username: username.value,
    password: password.value,
  };
  login(params)
    .then((res) => {
      console.log(res);
      loginLoading.value = false;
      userStore.setUserInfo(res);
      router.replace("/");
    })
    .catch((err) => {
      console.log(err);
      loginLoading.value = false;
    });
}
</script>

<style>
</style>
